import base from '@/common/config'
let ajaxTimer = 0
let sysInfo = uni.getSystemInfoSync()
let paddingTop = (sysInfo.statusBarHeight*2 + 124)+'rpx'

export default {
	data() {
		return {
			imgBaseUrl: base.imgBaseUrl,
			imgBaseUrl2: base.imgBaseUrl2,
			paddingTop,
			// ajaxTimer : 0,
		}
	},
	methods: {
		// 上传功能需要在app上,h5端上传会失败
		uploadFile(_url, files, formData, imgName) {
			uni.showLoading({
				title: '正在上传',
			})
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: base.baseUrl + _url,
					header: {
						'content-type': 'multipart/form-data', //ios一定要加请求头
						// 'content-type': 'application/x-www-form-urlencoded',
					},
					formData,
					filePath: files,
					// files,
					name: imgName,
					// data: formData,
					success: (uploadFileRes) => {
						console.log('sucess')
						uni.hideLoading()
						// uni.showToast({
						// 	title: '上传成功',
						// 	duration: 3000,
						// 	icon: 'success'
						// });
						resolve(uploadFileRes)
					},
					fail(err) {
						console.log('error')
						console.log(err)
					},
					complete(res) {
						console.log('我完成了', res)
					},
				})
			})
		},
		// date 时间戳  格式化日期
		dateformat(date) {
			function add0(m) {
				return m < 10 ? '0' + m : m
			}
			//date是整数，否则要parseInt转换
			var time = new Date(date)
			var y = time.getFullYear()
			var m = time.getMonth() + 1
			var d = time.getDate()
			var h = time.getHours()
			var mm = time.getMinutes()
			var s = time.getSeconds()
			return (
				y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s)
			)
		},
		// 获取微信code
		getwxCode() {
			let _this = this
			// #ifdef MP-WEIXIN
			return new Promise((resolve, reject)=>{
				wx.login({
					// onlyAuthorize: true,
					success(res) {
						let code = res.code
						resolve(code)
					},
				})
			})
			
			// #endif
		},
		//页面跳转   如goPage('/pages/prefile/my-collage/my-collage' , {})
		goPage(url, query = {}) {
			if (!url) {
				return this.setMessage('该功能即将上线!')
			}
			this.$Router.push({
				path: url,
				query: query
			})
		},
		replacePage(url, query = {}) {
			this.$Router.replace({
				path: url,
				query: query
			})
		},
		once(fn) {
			// 只执行一次函数
			let done = false
			return function() {
				if (!done) {
					done = true
					return fn.apply(this, arguments)
				}
			}
		},
		// 返回上一页
		goBack(_page = 1) {
			this.once(() => {
				let pages = getCurrentPages()
				// console.log(pages);
				if (pages.length == 1) {
					this.goTabBar('/pages/index/index')
				}else{
					// console.log('执行了');
					uni.navigateBack({
						delta: _page,
					})
				}
				
			})()
		},
		// 长按保存到本地
		saveImg(url,isNet=true) {
			//是否网络图片
			if(isNet){
			uni.downloadFile({
				url,
				success: (res) => {
					console.log(res.tempFilePath)
					// 获取到图片本地地址后再保存图片到相册(因为此方法不支持远程地址)
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => {
							uni.showToast({
								title: '保存成功！',
							})
						},
						fail: (err) => {
							
							console.log(err)
							 wx.openSetting({
							              success(settingdata) {
							                if (settingdata.authSetting['scope.writePhotosAlbum']) {
							                  wx.showModal({
							                    title: '提示',
							                    content: '获取权限成功,再次保存图片即可成功',
							                    showCancel: false,
							                  })
							                } else {
							                  wx.showModal({
							                    title: '提示',
							                    content: '获取权限失败，无法保存到相册',
							                    showCancel: false,
							                  })
							                }
							
							              },
							              complete(comp) {
							                // console.log("complete", finishData)
							              }
							            })
						},
					})
				},
			})
			}else{
				uni.saveImageToPhotosAlbum({
					filePath: url,
					success: () => {
						uni.showToast({
							title: '保存成功！',
						})
					},
					fail: (err) => {
						
						console.log(err)
						 wx.openSetting({
						              success(settingdata) {
						                if (settingdata.authSetting['scope.writePhotosAlbum']) {
						                  wx.showModal({
						                    title: '提示',
						                    content: '获取权限成功,再次保存图片即可成功',
						                    showCancel: false,
						                  })
						                } else {
						                  wx.showModal({
						                    title: '提示',
						                    content: '获取权限失败，无法保存到相册',
						                    showCancel: false,
						                  })
						                }
						
						              },
						              complete(comp) {
						                // console.log("complete", finishData)
						              }
						            })
					},
				})
			}
		},
		//跳转到tabbar
		goTabBar(url) {
			uni.switchTab({
				url,
			})
		},
		// 获取设备信息
		getSystemInfo() {
			let platformSource = ''
			// #ifdef MP-WEIXIN
			platformSource = 'miniApps'
			// #endif

			// #ifdef APP
			let info = uni.getSystemInfoSync()
			if (info.platform == 'android') {
				platformSource = 'android'
			} else {
				platformSource = 'ios'
			}
			// #endif

			return platformSource
		},
		// 设置页标题
		setPageTitle(title) {
			uni.setNavigationBarTitle({
				title,
			})
		},
		// 设置提示语
		setMessage(title, duration = 2000) {
			if(!title) return
			uni.showToast({
				title,
				icon: 'none',
				duration
			})
		},
		// 千分位用逗号隔开
		NumberFormatter(num, radix) {
			if (isNaN(num)) return 0
			radix = radix || 1
			let arr = (parseFloat(num) / radix).toFixed(2).split('.')
			return parseFloat(arr[0]).toLocaleString() + '.' + arr[1]
		},
		// 处理金额方法
		handledMoneyMethod(val) {
			if (!val) {
				return 0
			}
			let value = Math.round(parseFloat(val) * 100) / 100
			let xsd = value.toString().split('.')
			if (xsd.length == 1) {
				value = value.toString() + '.00'
				return value
			}
			if (xsd.length > 1) {
				if (xsd[1].length < 2) {
					value = value.toString() + '0'
				}
				return value
			}
		},
		// 复制
		copy(_text) {
			let that = this
			uni.setClipboardData({
				data: _text,
				success() {
					that.setMessage('复制成功！')
				}
			})
		},
		// 进入企业客服
		contactService() {

			console.log('进入企业微信客服');
			//// #ifdef MP-WEIXIN
			wx.openCustomerServiceChat({
				extInfo: {
					url: base.enterpriseWeChatServiceUrl
				},
				corpId: base.corpId,
				success(res) {
					console.log('进入成功');
					console.log(res);
				},
				fail(err) {
					console.log('进入失败');
					console.log(err);
				}

			})
			//// #endif
		},
		// 节流
		throttle(func, wait, options) {
			let _this, args, timeout;
			let old = 0; //时间戳
			//如果没有options就将其设置为空对象
			if (!options) options = {};

			let later = function() {
				old = new Date().valueOf();
				timeout = null;
				func.apply(_this, args);
			}
			return function() {
				_this = this;
				args = arguments;
				let now = new Date().valueOf();
				if (options.leading === false && !old) {
					old = now;
				}
				if (now - old > wait) {
					// 第一次直接执行
					if (timeout) {
						clearTimeout(timeout);
						timeout = null;
					}
					func.apply(_this, args);
					old = now;
				} else if (!timeout && options.trailing !== false) {
					//最后一次也被执行
					timeout = setTimeout(later, wait)
				}
		 }
		},
		// 记录登录次数
		loginRecord() {
			return this.$http({
				url: '/meiyi-web/api/empnologinlogcount.ed',
			}).then(res => {})
		},
		debounce(fn, delay = 1000) {
		 let t = null
			return function() {
				clearTimeout(t)
				t = setTimeout((args) => {
					fn.apply(this, args)
				}, delay)
			}
		},
		// 防抖
		lazyFunction(fn, timeout) {
			console.log('1111');
			return function() {
				if (ajaxTimer) clearTimeout(ajaxTimer);
				let args = arguments
				ajaxTimer = setTimeout(() => {
					fn.apply(this, args)
				}, timeout);
			};
		},
		// 返回天数
		handlerDateDurationCurrent(time) {
			let d1 = new Date(time)
			let d2 = new Date()

			let cha = Math.abs(d2.getTime() - d1.getTime())
			let days = parseInt(cha / (24 * 60 * 60 * 1000))
			let hours = parseInt(cha % (24 * 60 * 60 * 1000) / (60 * 60 * 1000))
			let mins = parseInt(cha % (60 * 60 * 1000) / (60 * 1000))
			if (days) {
				// return `+ ${days}d ${hours}h ${mins}m`
				return `${days}天`
			} else if (hours) {
				return `+ ${hours}h ${mins}m`
			} else {
				return `+ ${mins}m`
			}
		},
		// 截取字符最后一位
		subLastStr(str){
			if(!str) return ''
			let text = ''
			text = str.substring(0,str.length-1)
			return text
		},
		// 导出excel等文件
		exportFile(url){
			const downloadTask = uni.downloadFile({
				url: base.baseUrl + url,
				success: function(res) {
					var filePath = res.tempFilePath;
					uni.openDocument({
						filePath: filePath,
						showMenu: true,
						success: function(res) {
							console.log('打开文档成功');
						}
					});
				},
				fail: () => {
					this.setMessage('操作失败！')
				}
				
			});
			downloadTask.onProgressUpdate((res) => {
				console.log('下载进度' + res.progress);
				console.log('已经下载的数据长度' + res.totalBytesWritten);
				console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
			});
		},
		handleMemberStatusDir(val){
			let data ={
				'01' : '在职',
				'02' : '在学',
				'03' : '离职',
				'04' : '退养',
				'05' : '退休',
				'06' : '即将离职',
				'09' : '黑名单',
			}
			return data[val]
		}
	},
	filters: {
		// 数字控制判断
		numberEmptyJudge(val) {
			return val ? val : 0
		},
		// 字符串 文字处理
		emptyStr(val) {
			return val ? val : ''
		},
		// 处理打折
		handlediscountVal(_val) {
			return _val * 10
		},
		// 不足两位补零
		handledMoney(val) {
			if (!val) {
				return 0
			}
			let value = Math.round(parseFloat(val) * 100) / 100
			let xsd = value.toString().split('.')
			if (xsd.length == 1) {
				value = value.toString() + '.00'
				return value
			}
			if (xsd.length > 1) {
				if (xsd[1].length < 2) {
					value = value.toString() + '0'
				}
				return value
			}
		},
		dateformat(date) {
			function add0(m) {
				return m < 10 ? '0' + m : m
			}
			//date是整数，否则要parseInt转换
			var time = new Date(date)
			var y = time.getFullYear()
			var m = time.getMonth() + 1
			var d = time.getDate()
			var h = time.getHours()
			var mm = time.getMinutes()
			var s = time.getSeconds()
			return (
				y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s)
			)
		},
	},
}
